package com.bsoft.exchange.service;

import com.bsoft.exchange.dao.his.CreateOrderNoMapper;
import com.bsoft.exchange.dao.his.HospitalizationMapper;
import com.bsoft.exchange.dao.his.SystemConfigMapper;
import com.bsoft.exchange.dao.portal.HospitalInformationMapper;
import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.pojo.*;
import com.bsoft.exchange.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 创建日期 : 2019/10/14
 * 创建人 : 赵太行
 */
@Service
public class HospitalizationCostService {
    @Autowired
    HospitalizationMapper hospitalizationMapper;
    @Autowired
    HospitalInformationMapper hospitalInformationMapper;
    @Autowired
    PublicService publicService;
    @Autowired
    IdentityManager identityManager;
    
    @Autowired
	CreateOrderNoService createOrderNoService;
    @Autowired
    SystemConfigMapper systemConfigMapper;
    
    @Autowired
	UserBillManager userBillManager;
    
    @Autowired
    CreateOrderNoMapper createOrderNoMapper;
    @Autowired
    CacheSupport cacheSupport;

    String ss = null;
    private Double credit;
    private String ssysName;
    private String ssysName2;
    private String mzysName;
    private String mzysName2;
    private String xshsName;
    private String xshsName2;
    private String xhhsName;
    private String xhhsName2;


    /**
     * 获取住院记录
     */
    public BaseResponse<List<HospitalizationRecordDomain>>getRecord(HospitalizationRecordPojo pojo){
        String brid = null;
        BaseResponse<List<HospitalizationRecordDomain>> baseResponse=new BaseResponse();
        if (pojo.getQueryType().equals(4)){
            if (TextUtils.isEmpty(pojo.getInHospitalRecordCode())){
                baseResponse.setCode(Constant.successResponse);
                baseResponse.setMessage("查询类型是4的时候住院号码不能为空");
                return baseResponse;
            }
        }else {
            if (pojo.getQueryType().equals(1)) {
                brid = pojo.getPatientId();
            } else {
                brid = publicService.getBRID(pojo.getOrganizationId(), pojo.getQueryType(), String.valueOf(pojo.getCardType()), pojo.getCardNumber(),
                        pojo.getPatientMedicalCardType(), pojo.getPatientMedicalCardNumber());
            }
            if (TextUtils.isEmpty(brid)) {
                baseResponse.setCode(Constant.successResponse);
                baseResponse.setMessage("查询不到该病人信息");
                return baseResponse;
            }
        }
        List<HospitalizationRecordDomain>dataList= hospitalizationMapper.getHospitalizationInfo(pojo.getOrganizationId(),
                brid,pojo.getQueryType(),pojo.getInHospitalRecordCode());
        if (dataList.size()==0){
            baseResponse.setMessage("该病人暂无住院记录");
            baseResponse.setCode(Constant.successResponse);
            return baseResponse;
        }
        List<BridFymx>bridFymx=hospitalizationMapper.getBridFymx(pojo.getOrganizationId(),brid,pojo.getQueryType(),pojo.getInHospitalRecordCode());
        List<HospitalInformation> hospitalInformationList=cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);

        for (HospitalizationRecordDomain data:dataList){
            for (BridFymx bridFymx1:bridFymx){
                if (data.getInHospitalRecordNumber().equals(bridFymx1.getZYH())){
                    data.setTotalFee(bridFymx1.getZJJE());
                    data.setSelfFee(bridFymx1.getZFJE());
                }
            }
            if (data.getCYPB()==0||data.getCYPB()==1||data.getCYPB()==2){
                data.setStatus("1");
            }else if (data.getCYPB()==8){
                data.setStatus("2");
            }else if (data.getCYPB()==9){
                data.setStatus("3");
            }else{
                data.setStatus("4");
            }

            //医保金额
            Double ybje= SumPriceUtil.getMinusPriceDouble(data.getTotalFee(),data.getSelfFee());
            data.setMedicalExpensesCost(ybje);
            //押金余额
            Double yjye= SumPriceUtil.getMinusPriceDouble(data.getTotalBalance(),data.getTotalFee());
            if (yjye<=0){
                data.setBalance(0.00);
            }else{
                data.setBalance(yjye);
            }

            if (data.getTotalBalance()==null){
                data.setTotalBalance(0.00);
            }
            for (HospitalInformation jgxx:hospitalInformationList){
                if (data.getOrganizationId().equals(jgxx.getOrganizationId())){
                    data.setOrganizationName(jgxx.getOrganizationName());
                }
            }
        }
        baseResponse.setMessage("查询成功");
        baseResponse.setCode(Constant.successResponse);
        baseResponse.setData(dataList);
        return baseResponse;
    }

    /**
     * 获取手术信息
     */
    public BaseResponse<List<SSXXDomain>>getSurgeryInfo(GetOperationInfoPojo pojo){

        BaseResponse<List<SSXXDomain>> baseResponse=new BaseResponse();
        List<SSXXDomain> dataList;

        try {
            if (pojo.getQueryType()==4) {
                dataList = hospitalizationMapper.getSurgeryInfo(pojo.getOrganizationId(),pojo.getOperationId(),null);
            }else if (pojo.getQueryType()==1){
                dataList = hospitalizationMapper.getSurgeryInfo(pojo.getOrganizationId(),null,pojo.getPatientIdList());
            } else{
                List<String> brid=publicService.getBRIDist(pojo.getOrganizationId(),pojo.getQueryType(),
                        pojo.getPatientIdentityCardList(),pojo.getPatientMedicalCardNumberList());
                if (brid.size()==0){
                    baseResponse.setCode(Constant.successResponse);
                    baseResponse.setMessage("没有该病人信息");
                    return baseResponse;
                }
                dataList = hospitalizationMapper.getSurgeryInfo(pojo.getOrganizationId(),null,brid);
            }
            List<HospitalInformation> yymcList = cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);

            if (dataList==null){
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("查询出错");
                return baseResponse;
            }
        List<DoctorInfo> ygxmList=publicService.getDoctorInfo(pojo.getOrganizationId());
        List<KsdmDomain> ksdmList= publicService.getKsdm(pojo.getOrganizationId());
        for (SSXXDomain data:dataList){
            ssysName=null;
            ssysName2=null;
            mzysName=null;
            mzysName2=null;
            xshsName=null;
            xshsName2=null;
            xhhsName=null;
            xhhsName2=null;
            if(!StringUtils.isEmpty(data.getSurgeon())){
                data.setSurgeon(sub(data.getSurgeon()));
            }
            if(!StringUtils.isEmpty(data.getAnesthesiologist())){
                data.setAnesthesiologist(sub(data.getAnesthesiologist()));
            }
            if(!StringUtils.isEmpty(data.getNurse())){
                data.setNurse(sub(data.getNurse()));
            }
            data.setOperativePlace("手术室");
             if (data.getAPBZ().equals(1)&&data.getSSBZ().equals(1)&&data.getWCBZ().equals(1)){
                data.setStatus(7);
                data.setStatusStr("手术结束");
            }else if (data.getAPBZ().equals(1)&&data.getMZBZ().equals(1)&&data.getMZWCBZ().equals(1)){
                data.setStatus(8);
                data.setStatusStr("麻醉结束");
            }else if (data.getAPBZ().equals(1)&&data.getSSBZ().equals(1)&&data.getWCBZ().equals(0)){
                data.setStatus(6);
                data.setStatusStr("手术中");
            }else if (data.getAPBZ().equals(1)&&data.getMZBZ().equals(1)&&data.getMZWCBZ().equals(0)){
                 data.setStatus(5);
                 data.setStatusStr("麻醉中");
             }else if (data.getAPBZ().equals(1)&&data.getMZBZ().equals(0)){
                data.setStatus(4);
                data.setStatusStr("已安排");
            }else{
                data.setStatus(3);
                data.setStatusStr("待安排");
            }

            if (TextUtils.isEmpty(data.getOperatingRoom())){
                data.setOperatingRoom("暂无安排");
            }
            if (TextUtils.isEmpty(data.getConsiderations())){
                data.setConsiderations("暂无注意事项");
            }
            for (DoctorInfo doctorInfo:ygxmList){
                if (!TextUtils.isEmpty(data.getSSYS())) {
                    if (doctorInfo.getYGDM().equals(data.getSSYS())) {
                        ssysName = doctorInfo.getYGXM();
                    }
                }
                if (!TextUtils.isEmpty(data.getSSYS_2())){
                    if (doctorInfo.getYGDM().equals(data.getSSYS_2())) {
                        ssysName2 = doctorInfo.getYGXM();
                    }
                }
                if (!TextUtils.isEmpty(data.getMZYS())){
                    if (doctorInfo.getYGDM().equals(data.getMZYS())) {
                        mzysName = doctorInfo.getYGXM();
                    }
                }
                if (!TextUtils.isEmpty(data.getMZYS_2())){
                    if (doctorInfo.getYGDM().equals(data.getMZYS_2())) {
                        mzysName2 = doctorInfo.getYGXM();
                    }
                }
                if (!TextUtils.isEmpty(data.getXSHS())){
                    if (doctorInfo.getYGDM().equals(data.getXSHS())) {
                        xshsName = doctorInfo.getYGXM();
                    }
                }
                if (!TextUtils.isEmpty(data.getXSHS_2())){
                    if (doctorInfo.getYGDM().equals(data.getXSHS_2())) {
                        xshsName2 = doctorInfo.getYGXM();
                    }
                }
                if (!TextUtils.isEmpty(data.getXHHS())){
                    if (doctorInfo.getYGDM().equals(data.getXHHS())) {
                        xhhsName = doctorInfo.getYGXM();
                    }
                }
                if (!TextUtils.isEmpty(data.getXHHS_2())){
                    if (doctorInfo.getYGDM().equals(data.getXHHS_2())) {
                        xhhsName2 = doctorInfo.getYGXM();
                    }
                }
            }
            data.setSurgeon(stringToString(ssysName,ssysName2,null,null));
            data.setAnesthesiologist(stringToString(mzysName,mzysName2,null,null));
            data.setNurse(stringToString(xshsName,xshsName2,xhhsName,xhhsName2));
            for (KsdmDomain ksdmDomain:ksdmList){
                if (ksdmDomain.getKSDM().equals(data.getDepartmentCode())){
                    data.setDepartmentName(ksdmDomain.getKSMC());
                    break;
                }
            }
            for (HospitalInformation yymc:yymcList){
                if (yymc.getOrganizationId().equals(data.getOrganizationId())){
                    data.setOrganizationName(yymc.getOrganizationName());
                }
            }
        }
        } catch (SQLException e) {
            e.printStackTrace();
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("数据库出错");
            return baseResponse;
        }
        baseResponse.setMessage("查询成功");
        baseResponse.setCode(Constant.successResponse);
        baseResponse.setData(dataList);
        return baseResponse;
    }

    public String sub(String s){
        ss=s.substring(0,s.length()-1);
        return ss;
    }
    /**
     * 获取预缴金记录
     */
    public BaseResponse getAdvacedPaymentList(AdvancedPaymentListPojo pojo){
        BaseResponse<List<AdvancedPaymentListDomain>> baseResponse=new BaseResponse();
        String brid = null;
        try {
            if (pojo.getQueryType().equals(1)){
                brid=pojo.getPatientId();
            }else {
                if (pojo.getQueryType() != 4) {
                    brid = publicService.getBRID(pojo.getOrganizationId(),pojo.getQueryType(), String.valueOf(pojo.getCardType()), pojo.getCardNumber(),
                            pojo.getPatientMedicalCardType(), pojo.getPatientMedicalCardNumber());
                    if (TextUtils.isEmpty(brid)) {
                        baseResponse.setCode(Constant.successResponse);
                        baseResponse.setMessage("查询不到该病人信息");
                        return baseResponse;
                    }
                } else {
                    if (TextUtils.isEmpty(pojo.getInHospitalRecordNumber())) {
                        baseResponse.setCode(Constant.errorTag);
                        baseResponse.setMessage("状态为4的情况下住院号不能为空");
                        return baseResponse;
                    }
                }
            }
            List<AdvancedPaymentListDomain> dataList = hospitalizationMapper.listPaymentHistory(pojo.getOrganizationId(), brid,
                    pojo.getInHospitalRecordNumber(),pojo.getQueryType());
            if (dataList.size()>0) {
                List<HospitalInformation> hospitalInformationList = cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);

                for (AdvancedPaymentListDomain advancedPaymentListDomain : dataList) {
                    for (HospitalInformation jgxx:hospitalInformationList){
                        if (advancedPaymentListDomain.getOrganizationId().equals(jgxx.getOrganizationId())){
                            advancedPaymentListDomain.setOrganizationName(jgxx.getOrganizationName());
                        }
                    }
//                    for (AdvancedPaymentDetailsDomain domain:advancedPaymentListDomain.getPaymentRecord()){
//                        //进行支付方式转换
//                        if (domain.getPayMode().equals("15")){
//                            //支付宝
//                            domain.setPayMode("支付宝");
//                        }else if (domain.getPayMode().equals("49")){
//                            //微信
//                            domain.setPayMode("微信");
//                        }else if (domain.getPayMode().equals("8")){
//                            //银联、pos机
//                            domain.setPayMode("银联");
//                        }else if (domain.getPayMode().equals("50")){
//                            //聚合支付支付宝
//                            domain.setPayMode("聚合支付-支付宝");
//                        }else if (domain.getPayMode().equals("51")){
//                            //聚合支付微信
//                            domain.setPayMode("聚合支付-微信");
//                        }else if (domain.getPayMode().equals("52")){
//                            //聚合支付POS机
//                            domain.setPayMode("聚合支付-银联");
//                        }
//                    }
                }
                baseResponse.setMessage("查询成功");
            }else{
                baseResponse.setMessage("暂未查询到预缴金记录");
            }
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setData(dataList);
        } catch (SQLException e) {
            e.printStackTrace();
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("数据库错误");
            return baseResponse;
        }
        return baseResponse;
    }
    /**
     * 获取住院每日费用集合
     */
    public BaseResponse getListHospitalizationPaymentDate(HospitalizationPaymentDatePojo pojo){
        BaseResponse baseResponse=new BaseResponse();
        String brid=null;
        try {
            if (pojo.getQueryType().equals(4)){
                if (TextUtils.isEmpty(pojo.getInHospitalRecordNumber())) {
                    baseResponse.setCode(Constant.errorTag);
                    baseResponse.setMessage("状态为4的情况下住院号不能为空");
                    return baseResponse;
                }
                if (TextUtils.isEmpty(pojo.getCostBeginDate())){
                    pojo.setCostBeginDate(null);
                }
                if (TextUtils.isEmpty(pojo.getCostEndDate())){
                    pojo.setCostEndDate(null);
                }
            }else {
                if (TextUtils.isEmpty(pojo.getCostBeginDate()) || TextUtils.isEmpty(pojo.getCostEndDate())) {
                    baseResponse.setCode(Constant.errorTag);
                    baseResponse.setMessage("不使用住院号查询时开始时间和结束时间不能为空");
                    return baseResponse;
                }
                if (pojo.getQueryType().equals(1)) {
                    brid = pojo.getPatientId();
                } else {
                    brid = publicService.getBRID(pojo.getOrganizationId(),pojo.getQueryType(), String.valueOf(pojo.getCardType()), pojo.getCardNumber(),
                            pojo.getPatientMedicalCardType(), pojo.getPatientMedicalCardNumber());
                }
                if (TextUtils.isEmpty(brid)) {
                    baseResponse.setCode(Constant.successResponse);
                    baseResponse.setMessage("查询不到该病人信息");
                    return baseResponse;
                }
            }
            HospitalizationPaymentDateDoamin dateDoamin = hospitalizationMapper.listHospitalizationPaymentDate(pojo.getOrganizationId(),
                    brid,pojo.getInHospitalRecordNumber(),pojo.getQueryType(),pojo.getCostBeginDate(),pojo.getCostEndDate());
            if(dateDoamin==null){
                baseResponse.setMessage("未查询到数据");
                baseResponse.setCode(Constant.successResponse);
                return baseResponse;
            }
            List<ChargeProject> sfxmList=publicService.getSfxm();
            CostDomain costDomain=hospitalizationMapper.getZyCostMoney(pojo.getOrganizationId(),dateDoamin.getInHospitalRecordNumber());
            if (costDomain!=null){
                Double zyzfy = costDomain.getFYHJ();//住院总费用
                //自费金额
                Double zfje = costDomain.getZFHJ();
                dateDoamin.setTotalFee(zyzfy);
                dateDoamin.setSelfFee(zfje);
                Double ybje=SumPriceUtil.getMinusPriceDouble(zyzfy,zfje);
                dateDoamin.setMedicalExpensesCost(ybje);//医保
            }

                    List<ZY_TBKKDomain> tbkkList = hospitalizationMapper.getZY_TBKK(Long.parseLong(pojo.getOrganizationId()),
                            Long.parseLong(dateDoamin.getInHospitalRecordNumber()));
                    Double jkhj=0.00;//住院总押金

                    //合并，
                    if(tbkkList != null && tbkkList.size() >0){
                        for(ZY_TBKKDomain tbkk : tbkkList){
                            jkhj =SumPriceUtil.getAddPriceDouble(jkhj,tbkk.getJkje());
                        }
                        dateDoamin.setTotalBalance(jkhj);
                        Double yjye=SumPriceUtil.getMinusPriceDouble(jkhj,dateDoamin.getTotalFee());//押金余额=押金-费用
                        if (yjye <= 0) {
                            dateDoamin.setBalance(0.00);
                        } else {
                            dateDoamin.setBalance(yjye);
                        }
                    }


                    for (CostDateListDomain costDateListDomain : dateDoamin.getCostDateList()) {
                        Double totalCost = 0.00;
                        for (MainCostListDomain mainCostListDomain : costDateListDomain.getMainCostList()) {
                            for (ChargeProject chargeProject:sfxmList){
                                if (chargeProject.getSFXM().equals(mainCostListDomain.getFYXM())){
                                    mainCostListDomain.setChargeName(chargeProject.getSFMC());
                                    break;
                                }
                            }
                            Double amount = 0.00;
                            for (CostListDoamin costListDoamin : mainCostListDomain.getCostList()) {
                                String name = costListDoamin.getFYMC();
                                int wz = name.indexOf("/");
                                if (wz>0){
                                    costListDoamin.setCostName(name.substring(0,wz));
                                }else{
                                    costListDoamin.setCostName(name);
                                }
                                int lastWz = name.lastIndexOf("/")+1;
                                if (lastWz > 0) {
                                    costListDoamin.setCostUnit(name.substring(lastWz,name.length()));
                                } else {
                                    costListDoamin.setCostUnit("次");
                                }
                                amount = amount + costListDoamin.getCostSubtotal();
                            }
                            mainCostListDomain.setAmount(amount);
                            totalCost = totalCost + amount;
                        }
                        costDateListDomain.setTotalCost(totalCost);
                    }
            List<HospitalInformation> hospitalInformationList = cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);
            for (HospitalInformation jgxx:hospitalInformationList){
                if (dateDoamin.getOrganizationId().equals(jgxx.getOrganizationId())){
                    dateDoamin.setOrganizationName(jgxx.getOrganizationName());
                }
            }
        baseResponse.setMessage("查询成功");
        baseResponse.setCode(Constant.successResponse);
        baseResponse.setData(dateDoamin);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return baseResponse;
    }
    /**
     * 获取住院总费用
     */
    public BaseResponse getListHospitalizationPayment(CostAggregationPojo pojo) {
        BaseResponse baseResponse = new BaseResponse();
            try{
            CostAggregationDoamin dateDoamin = hospitalizationMapper.getCostAggregation(pojo.getOrganizationId(),
                    pojo.getInHospitalRecordNumber());
                if (dateDoamin!=null) {
                    //住院总费用
                    Double zyzfy = 0.00;
                    //消费总金额
                    credit = 0.00;
                    List<ZY_TBKKDomain> tbkkList = hospitalizationMapper.getZY_TBKK(Long.parseLong(pojo.getOrganizationId()),
                            Long.parseLong(dateDoamin.getInHospitalRecordNumber()));
                    Double jkhj=0.00;//住院总押金

                    //合并，
                    if(tbkkList.size() >0){
                        for(ZY_TBKKDomain tbkk : tbkkList){
                            jkhj =SumPriceUtil.getAddPriceDouble(jkhj,tbkk.getJkje());
                        }
                    }
                    for (CostDomain jsCost : dateDoamin.getFyhjList()) {
                        zyzfy =SumPriceUtil.getAddPriceDouble(zyzfy,jsCost.getFYHJ());
                        credit =SumPriceUtil.getAddPriceDouble(credit,jsCost.getZFHJ());
                    }
                    dateDoamin.setCredit(credit);
                    dateDoamin.setTotalFee(zyzfy);
                    dateDoamin.setBalance(jkhj);
                    for (MainCostListDomain mainCostListDomain : dateDoamin.getMainCostList()) {
                        Double amount = 0.00;
                        for (CostListDoamin costListDoamin : mainCostListDomain.getCostList()) {
                            String name = costListDoamin.getFYMC();
                            int wz = name.indexOf("/");
                            if (wz>0){
                                costListDoamin.setCostName(name.substring(0,wz));
                            }else{
                                costListDoamin.setCostName(name);
                            }

                            int lastWz = name.lastIndexOf("/")+1;
                            if (lastWz > 0) {
                                costListDoamin.setCostUnit(name.substring(lastWz,name.length()));
                            } else {
                                costListDoamin.setCostUnit("次");
                            }
                            amount = amount + costListDoamin.getCostSubtotal();
                        }
                        mainCostListDomain.setAmount(amount);
                    }

                }else{
                    baseResponse.setMessage("未查询到数据");
                    baseResponse.setCode(Constant.successResponse);
                    return baseResponse;
                }
                List<HospitalInformation> hospitalInformationList = cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);
                for (HospitalInformation jgxx:hospitalInformationList){
                    if (dateDoamin.getOrganizationId().equals(jgxx.getOrganizationId())){
                        dateDoamin.setOrganizationName(jgxx.getOrganizationName());
                    }
                }
            baseResponse.setMessage("查询成功");
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setData(dateDoamin);
        } catch (SQLException e) {
            e.printStackTrace();
            baseResponse.setMessage("数据库出错");
            baseResponse.setCode(Constant.errorTag);
        }
        return baseResponse;
    }
    /**
     * 确认预缴金
     */
    @Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
    public BaseResponse confrimYJJ(HospitalizationDepositPojo pojo) throws Exception {
        BaseResponse baseResponse=new BaseResponse();
            Integer isRepetition=hospitalizationMapper
                    .verifyHospitalizationDeposit(pojo.getOrganizationId(),pojo.getAgtOrderNumber());
            if (isRepetition>0){
                baseResponse.setCode(Constant.successResponse);
                baseResponse.setMessage("该笔交易已经存在，请勿重复操作");
                return baseResponse;
            }
            //获取住院类别
            HospitalizationInfo zyInfo = hospitalizationMapper.getZyInfo(pojo.getOrganizationId(), pojo.getInHospitalRecordNumber());
            if (zyInfo==null){
                baseResponse.setCode(Constant.successResponse);
                baseResponse.setMessage("该住院号不存在");
                return baseResponse;
            }
            if (zyInfo.getZYLB() <= 0) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("获取住院类别失败");
                return baseResponse;
            }
            //进行支付方式转换
            if (pojo.getPayMode().equals(1)){
                //支付宝
                pojo.setPayMode(15);
            }else if (pojo.getPayMode().equals(2)){
                //微信
                pojo.setPayMode(41);
            }else if (pojo.getPayMode().equals(3)){
                //银联、pos机
                pojo.setPayMode(8);
            }else if (pojo.getPayMode().equals(4)){
                //聚合支付支付宝
                pojo.setPayMode(42);
            }else if (pojo.getPayMode().equals(5)){
                //聚合支付微信
                pojo.setPayMode(43);
            }else if (pojo.getPayMode().equals(6)){
                //聚合支付POS机
                pojo.setPayMode(44);
            }
            long jkxh = identityManager.getMax("ZY_TBKK", 1);
            //获取员工票据
            String kdys= systemConfigMapper.getValueByConfigName(Long.parseLong(pojo.getOrganizationId()), "ZSYY_MRGH");
            BaseResponse<String> sjhm=publicService.getPjdm(pojo.getOrganizationId(),kdys,2);
            if (sjhm.getCode().equals(Constant.errorTag)){
                baseResponse.setCode(Constant.successResponse);
                baseResponse.setMessage(sjhm.getMessage());
                return baseResponse;
            }
            hospitalizationMapper.hospitalizationDeposit(pojo, zyInfo.getZYLB(), jkxh,sjhm.getData(),kdys);
//            Long shddh = (Long)identityManager.getMax("GY_SHDDH", 1);
//            hospitalizationMapper.insertZY_TBKK_KZXX(pojo.getOrganizationId(),shddh,3,0,1,
//                                                     0,zyInfo.getBRID(),null,pojo.getPayAmount(),pojo.getPayMode(),pojo.getPayTime());
        Long shddh =identityManager.getMax("GY_SHDDH", 1);
        Date now = new Date();
        createOrderNoMapper.insertShddhAll(shddh.toString(),3,zyInfo.getBRID(),now,
                pojo.getPayAmount(),pojo.getPayMode(),Integer.parseInt(pojo.getOrganizationId()),1,1,
                pojo.getAgtOrderNumber(),sjhm.getData());
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("确认成功");
        return baseResponse;
    }
    
    /**
     * 获取出院费用预结算信息
     */
    @Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
    public BaseResponse getPrecalculatedFee(CostAggregationPojo pojo,Integer type) throws Exception {
        BaseResponse baseResponse=new BaseResponse();
        
        Long jgid;
        Long zyh;
        if(pojo.getOrganizationId() == null || "".equals(pojo.getOrganizationId())){
        	baseResponse.setCode(Constant.errorTag);
        	baseResponse.setMessage("医院识别代码不能为空!");
       	  
            return baseResponse;
        }
          
       jgid = Long.parseLong(pojo.getOrganizationId());

       if(pojo.getInHospitalRecordNumber() == null || "".equals(pojo.getInHospitalRecordNumber())){
       	baseResponse.setCode(Constant.errorTag);
       	baseResponse.setMessage("住院号不能为空!");
      	  
           return baseResponse;
       }
         
       zyh = Long.parseLong(pojo.getInHospitalRecordNumber());

        ZY_BRRYDomain brry = hospitalizationMapper.getBRRYById(jgid,zyh);
        
        if(brry == null ){
        	baseResponse.setCode(Constant.errorTag);
           	baseResponse.setMessage("未找到该住院号的住院记录!");
          	  
            return baseResponse;
        }
        
        if(brry.getCypb() >=8){
        	baseResponse.setCode(Constant.errorTag);
           	baseResponse.setMessage("患者已出院，不能再次出院结算!");
          	  
            return baseResponse;
        }
        
        
        GetPrecalculatedFeeDomain precalculatedFee = hospitalizationMapper.getPrecalculatedFee(jgid, zyh);
        if(precalculatedFee == null){
        	precalculatedFee = new GetPrecalculatedFeeDomain();
        	precalculatedFee.setTotalFee(0.00);
        	precalculatedFee.setPayAmount(0.00);
        }
        //获取预缴金
        Double tbkk = hospitalizationMapper.getTbkk(jgid, zyh);

        if(tbkk ==null){
            tbkk= 0.00;
        }
        if(tbkk > precalculatedFee.getPayAmount()){
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("患者预缴金大于自负金额，请去线下医院办理出院结算退款!");

            return baseResponse;
        }
        //自负金额为 总自负金额-预缴金 zfje-tbkk
        Double zfje ;
        zfje = SumPriceUtil.getMinusPriceDouble(precalculatedFee.getPayAmount(),tbkk);
        if(zfje <0){
            zfje = 0.00;
        }
        precalculatedFee.setPayAmount(zfje);

        if( type == 0){
        	//预结算标识 
            String outOrderNumber ="";
            Double amount = precalculatedFee.getPayAmount();
    		//try {
    			//获取商户订单号  	业务类别：1，挂号，2 诊间支付，3预缴金充值，4住院结算
    			int zffs = 0;
    			BaseResponse<String> orderResponse = createOrderNoService.createShddh(jgid.intValue(), 4, zffs, amount, brry.getBrid().intValue());
    			
    			if(orderResponse.getCode() != Constant.successTag){
    				baseResponse.setCode(orderResponse.getCode());
    	            baseResponse.setMessage(orderResponse.getMessage());
    	            
    	            return baseResponse;
    			}
    			
    			outOrderNumber = orderResponse.getData();
    			
    		/*} catch (Exception e) {
    			e.printStackTrace();
    			baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("获取预结算标识(商户订单号)失败!");
                
                return baseResponse;
    		}*/
            /*if(1 ==1){
                throw new Exception("测试异常");
            }*/
    		precalculatedFee.setPaymentBudgetNumber(outOrderNumber);
        }

        baseResponse.setCode(Constant.successResponse);
        baseResponse.setMessage("确认成功");
        baseResponse.setData(precalculatedFee);
        
        return baseResponse;
    }
    /**
     * 提交出院结算信息
     * 
     * 提交结算逻辑由his提供罗列
     * 
     */
    @Transactional(value="hisTransactionManager",rollbackFor = Exception.class)
    public BaseResponse submitPaySettlement(PaySettlementPojo pojo) throws Exception {
        BaseResponse baseResponse=new BaseResponse();
        //进行支付方式转换
        if (pojo.getPayMode().equals("1")){
            //支付宝
            pojo.setPayMode("15");
        }else if (pojo.getPayMode().equals("2")){
            //微信
            pojo.setPayMode("41");
        }else if (pojo.getPayMode().equals("3")){
            //银联、pos机
            pojo.setPayMode("8");
        }else if (pojo.getPayMode().equals("4")){
            //聚合支付支付宝
            pojo.setPayMode("42");
        }else if (pojo.getPayMode().equals("5")){
            //聚合支付微信
            pojo.setPayMode("43");
        }else if (pojo.getPayMode().equals("6")){
            //聚合支付POS机
            pojo.setPayMode("44");
        }
       /* try {
*/
        	//1、数据校验 住院号有效判断，出院判别 <8
        	 //调用预结算接口，判断费用金额是否匹配，还有预结算的一些数据校验
            CostAggregationPojo costAggregationPojo = new CostAggregationPojo();
            costAggregationPojo.setInHospitalRecordNumber(pojo.getInHospitalRecordNumber());
            costAggregationPojo.setOrganizationId(pojo.getOrganizationId());
			BaseResponse costAg = getPrecalculatedFee(costAggregationPojo,1);
			
			//判断预结算是否成功
			if(( costAg.getCode() != Constant.successTag && costAg.getCode() != Constant.successResponse) || costAg.getData() == null){
				baseResponse.setCode(costAg.getCode());
				baseResponse.setMessage(costAg.getMessage());
				return baseResponse;
			}
			GetPrecalculatedFeeDomain yjsData = (GetPrecalculatedFeeDomain) costAg.getData();
			
			//判断预结算金额和传入金额是否相等
			if(new BigDecimal(pojo.getPayAmount()+ "").compareTo(new BigDecimal(yjsData.getPayAmount()+ "")) != 0){
				baseResponse.setCode(Constant.errorTag);
				baseResponse.setMessage("传入的付款金额【"+pojo.getPayAmount()+"】和单据实际金额不相等【"+yjsData.getPayAmount()+"】");
				return baseResponse;
			}
			
			//预结算已经判断过，这里可以直接获取转换
			 Long jgid;
		     Long zyh; 
		     jgid = Long.parseLong(pojo.getOrganizationId());
		     zyh = Long.parseLong(pojo.getInHospitalRecordNumber());
		     
		     //GY_SHDDHDomain shddh = createOrderNoMapper.getShddhById(pojo.getOutOrderNumber(),jgid);
             GY_SHDDHDomain shddh = createOrderNoMapper.getShddhById(pojo.getPaymentBudgetNumber(),jgid);
		     if(shddh == null){
		    	baseResponse.setCode(Constant.errorTag);
				baseResponse.setMessage("未找到该预结算标识【"+pojo.getPaymentBudgetNumber()+"】的记录");
				return baseResponse;
		     }
		     
		     ZY_BRRYDomain brry = hospitalizationMapper.getBRRYById(jgid,zyh);
		        
			//2、住院发票号码获取
			//获取默认工号
			String mrgh = systemConfigMapper.getValueByConfigName(jgid, "ZSYY_MRGH");
			
			String fphm = userBillManager.getSjhm_ZY(jgid, mrgh);
			
			if(fphm == null || "".equals(fphm)){
		    	baseResponse.setCode(Constant.errorTag);
				baseResponse.setMessage("获取默认工号【"+mrgh+"】的发票号码失败，请检查是否维护！");
				return baseResponse;
		     }
			
			//数据准备
			//获取ZY_TBKK
			List<ZY_TBKKDomain> tbkkList = hospitalizationMapper.getZY_TBKK(jgid,zyh);
			String sjhm="";
			Double jkhj=0.00;
			
			//合并，
			if(tbkkList != null && tbkkList.size() >0){
				for(ZY_TBKKDomain tbkk : tbkkList){
					jkhj += tbkk.getJkje();
					sjhm += ","+tbkk.getSjhm();
				}
				//最后去掉第一个 ","
				sjhm = sjhm.substring(1);
			}
			
			//获取默认住院类别
			Long zylb = hospitalizationMapper.getMrZylb(jgid,mrgh);
			
			//默认1
			if(zylb == null || zylb == 0){
				zylb = 1L;
			}
			
			//结算次数 + 1
			Integer jscs = brry.getJscs() + 1;
			
			//3、开始保存数据
			
			Date czrq = new Date();
			
			//插入ZY_ZYJS
			ZY_ZYJSDomain zyjs = new ZY_ZYJSDomain();
			
			zyjs.setZyh(zyh);
			zyjs.setJscs(jscs);
			zyjs.setJgid(jgid);
			zyjs.setJslx(5);  //默认出院结算
			zyjs.setKsrq(brry.getKsrq());
			zyjs.setZzrq(czrq);
			zyjs.setJsrq(czrq);
			zyjs.setFyhj(yjsData.getTotalFee());
			zyjs.setZfhj(yjsData.getPayAmount());
			zyjs.setJkhj(jkhj);
			zyjs.setFphm(fphm);
			zyjs.setCzgh(mrgh);
			zyjs.setZfpb(0);
			zyjs.setJsjk(sjhm);
			zyjs.setBrxz(brry.getBrxz());
			zyjs.setZylb(zylb);
			zyjs.setCzlx("住院结算");
			zyjs.setCzbq(brry.getBrbq());
			
			hospitalizationMapper.saveZYjs(zyjs);
			
			//更新发票号码,会自动判断申领完
			userBillManager.updateSjhm_ZY(jgid, mrgh, fphm);
			
			//更新住院各业务表的结算次数

			//更新ZY_TBKK
			hospitalizationMapper.updateJscsTbkk(zyh, jscs);
			
			//更新ZY_FYMX
			hospitalizationMapper.updateJscsFymx(zyh, jscs);
			
			//插入ZY_JSMX
			hospitalizationMapper.saveZY_JSMX(zyh, jscs);
			
			//更新ZY_BRRY
			hospitalizationMapper.updateJscsBrry(zyh, jscs, czrq);
			
			//更新商户订单号中间表
			//createOrderNoMapper.updateShddhYwzt(pojo.getOutOrderNumber(), 1, jgid.intValue());
            createOrderNoMapper.updateShddhYwzt(pojo.getPaymentBudgetNumber(), 1, jgid.intValue());
            createOrderNoMapper.updateShddhZfzt(pojo.getPaymentBudgetNumber(),1,new Date(),Integer.parseInt(pojo.getPayMode()),
                    jgid.intValue(),pojo.getAgtOrderNumber(),fphm);
            /*if(1 ==1){
                throw new Exception("测试异常");
            }*/

		/*} catch (Exception e) {
			e.printStackTrace();
			baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("出院结算失败!");
            return baseResponse;
		}*/
        
        baseResponse.setData(pojo.getNotify());
 
        baseResponse.setCode(Constant.successResponse);
        baseResponse.setMessage("确认成功");
        return baseResponse;
    }

    /**
     * 获取出院费用信息
     * @param pojo
     * @return
     */

    public BaseResponse getDischargeSettlementInfo(BasePojo pojo){
        BaseResponse baseResponse=new BaseResponse();
        List<String> ryzdmcList = new ArrayList<>();
        List<String> cyzdmcList = new ArrayList<>();
        String brid;
        if (pojo.getQueryType().equals(1)){
            brid=pojo.getPatientId();
        }else {
                brid = publicService.getBRID(pojo.getOrganizationId(),pojo.getQueryType(), String.valueOf(pojo.getCardType()), pojo.getCardNumber(),
                        pojo.getPatientMedicalCardType(), pojo.getPatientMedicalCardNumber());
                if (TextUtils.isEmpty(brid)) {
                    baseResponse.setCode(Constant.successResponse);
                    baseResponse.setMessage("查询不到该病人信息");
                    return baseResponse;
                }
        }
        DischargeSettlementInfoDomain data=hospitalizationMapper.dischargeSettlementInfo(pojo.getOrganizationId(),brid);
        if (data==null){
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("查询不到该病人出院结算信息");
            return baseResponse;
        }
        if (TextUtils.isEmpty(data.getLeaveHospitalDate())){
            data.setLeaveHospitalDate(TimeUtil.getNowDate());
        }else{
            data.setLeaveHospitalDate(data.getLeaveHospitalDate().substring(0,19));
        }
        CostDomain costDomain=hospitalizationMapper.getJsje(pojo.getOrganizationId(),data.getInHospitalRecordNumber());
        if (costDomain==null){
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("查询不到该病人的出院结算信息");
            return baseResponse;
        }else{
            if(costDomain.getFYHJ()==0){
                baseResponse.setCode(Constant.successResponse);
                baseResponse.setMessage("该病人没有结算信息或者已经结算");
                return baseResponse;
            }
        }
        List<DiagnosisDoamin>getDiagnosisInfoData=hospitalizationMapper.getDiagnosisInfo(pojo.getOrganizationId(),
                String.valueOf(data.getInHospitalRecordNumber()));
        for (DiagnosisDoamin dd:getDiagnosisInfoData){
            if (dd.getZDLX()==5){
                cyzdmcList.add(dd.getMSZD());
            }else {
                ryzdmcList.add(dd.getMSZD());
            }
        }

        String cyzd=List2String.listToString(cyzdmcList);
        data.setLeaveHospitalDiagnosis(cyzd);
        String ryzd=List2String.listToString(ryzdmcList);
        data.setHospitalizedDiagnosis(ryzd);

        data.setTotalCost(costDomain.getFYHJ());
        data.setDepositCost(costDomain.getJKJE());
        //代缴金额=自费金额-押金
        Double djje=SumPriceUtil.getMinusPriceDouble(costDomain.getZFHJ(),costDomain.getJKJE());
        if (djje<=0){
            data.setPaymentPendingCost(0.00);
        }else{
            data.setPaymentPendingCost(djje);
        }
        double ybje=costDomain.getFYHJ()-costDomain.getZFHJ();
        if (ybje<=0){
            data.setCostType("01");
        }else{
            data.setCostType("02");
            data.setMedicalExpensesCost(ybje);
        }
        if (data.getBRXB()==null){
            data.setPatientSex("未知");
        }else {
            if (data.getBRXB().equals(1)) {
                data.setPatientSex("男");
            } else if (data.getBRXB().equals(2)) {
                data.setPatientSex("女");
            }
        }
        List<HospitalInformation> hospitalInformationList = cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);
        for (HospitalInformation jgxx:hospitalInformationList){
            if (data.getOrganizationId().equals(jgxx.getOrganizationId())){
                data.setOrganizationName(jgxx.getOrganizationName());
            }
        }
        baseResponse.setMessage("查询成功");
        baseResponse.setCode(Constant.successResponse);
        baseResponse.setData(data);
        return baseResponse;
    }

    private String stringToString(String str1,String str2,String str3,String str4) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(str1)){
            sb.append(str1).append(",");
        }
        if (!TextUtils.isEmpty(str2)){
            sb.append(str2).append(",");
        }
        if (!TextUtils.isEmpty(str3)){
            sb.append(str3).append(",");
        }
        if (!TextUtils.isEmpty(str4)){
            sb.append(str4).append(",");
        }
        if (str1==null&&str2==null&&str3==null&&str4==null){
            return null;
        }
            return sb.toString().substring(0, sb.toString().length() - 1);
        }
    /**
     * 获取出院带药信息
     */
    public BaseResponse getDischargeMedicationInformation(AdvancedPaymentListPojo pojo){
        BaseResponse<List<GetDischargeMedDomain>> baseResponse=new BaseResponse();
        String brid = null;
        try {
            if ("1".equals(pojo.getQueryType().toString())){
                brid=pojo.getPatientId();
            }else {
                if (!"4".equals(pojo.getQueryType().toString())) {
                    brid = publicService.getBRID(pojo.getOrganizationId(),pojo.getQueryType(), String.valueOf(pojo.getCardType()), pojo.getCardNumber(),
                            pojo.getPatientMedicalCardType(), pojo.getPatientMedicalCardNumber());
                    if (TextUtils.isEmpty(brid)) {
                        baseResponse.setCode(Constant.successResponse);
                        baseResponse.setMessage("查询不到该病人信息");
                        return baseResponse;
                    }
                } else {
                    if (TextUtils.isEmpty(pojo.getInHospitalRecordNumber())) {
                        baseResponse.setCode(Constant.errorTag);
                        baseResponse.setMessage("状态为4的情况下住院号不能为空");
                        return baseResponse;
                    }
                }
            }
            List<GetDischargeMedDomain> dataList = hospitalizationMapper.getDischargeMedicationInformation(pojo.getOrganizationId(), brid,
                    pojo.getInHospitalRecordNumber(),pojo.getQueryType());
            String dischargeDiagnosis = "";
            if (dataList.size()>0) {
                List<HospitalInformation> hospitalInformationList = cacheSupport.getJgmcList(pojo.getOrganizationId(), pojo.getOrganizationId()+"jgmc",hospitalInformationMapper);
                for (GetDischargeMedDomain advancedPaymentListDomain : dataList) {

                    List<DiagnosisDoamin> diagnosisDoaminList = hospitalizationMapper.getDiagnosisInfo(pojo.getOrganizationId(),advancedPaymentListDomain.getInHospitalRecordNumber());
                    dischargeDiagnosis = "";
                    for(DiagnosisDoamin diagnosis:diagnosisDoaminList){
                        if("5".equals(diagnosis.getZDLX().toString())){
                            dischargeDiagnosis +=","+diagnosis.getMSZD();
                        }
                    }
                    if(dischargeDiagnosis != null && !"".equals(dischargeDiagnosis)){
                        dischargeDiagnosis = dischargeDiagnosis.substring(1);
                    }

                    advancedPaymentListDomain.setDischargeDiagnosis(dischargeDiagnosis);
                    if(advancedPaymentListDomain.getPatientSex().equals("1")){
                        advancedPaymentListDomain.setPatientSex("男");
                    }else{
                        advancedPaymentListDomain.setPatientSex("女");
                    }
                    for (HospitalInformation jgxx:hospitalInformationList){
                        if (advancedPaymentListDomain.getOrganizationId().equals(jgxx.getOrganizationId())){
                            advancedPaymentListDomain.setOrganizationName(jgxx.getOrganizationName());
                        }
                    }
                }
                baseResponse.setMessage("查询成功");
            }else{
                baseResponse.setMessage("暂未查询到出院带药信息");
            }

            baseResponse.setCode(Constant.successResponse);
            baseResponse.setData(dataList);
        } catch (SQLException e) {
            e.printStackTrace();
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("数据库错误");
            return baseResponse;
        }
        return baseResponse;
    }

    public BaseResponse getBalance(String sfzh) {
        BaseResponse<PrepareBalance> baseResponse = new BaseResponse<>();
        try {
            PrepareBalance prepareBalance = new PrepareBalance();
            prepareBalance = hospitalizationMapper.getBalance(sfzh);
            if (null==prepareBalance){

                baseResponse.setCode(Constant.successResponse);
                baseResponse.setMessage("未获取预缴费信息");
                return baseResponse;
            }
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setData(prepareBalance);
            return baseResponse;
        }catch (SQLException e){
            e.printStackTrace();
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("数据库错误");
            return baseResponse;
        }
    }
}
